package rs.thread.processor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import rs.domain.Tag;
import rs.domain.Track;
import rs.parser.RecommendedTrackParser;
import rs.thread.OnerousProcessor;
import rs.util.Requester;
import rs.util.TuningParameters;

/* Classe che, dato un tag, ne recupera i migliori brani associati a quel tag.
 * Ad ogni brano viene associato un peso pari al peso di quel tag. */
public class RecommendedTrackProcessor implements OnerousProcessor<Tag> {
	
	private Map<Track, Double> track2ranking;
	private Lock lock;
	private RecommendedTrackParser parser;
	
	public RecommendedTrackProcessor() {
		this.track2ranking = new HashMap<Track, Double>();
		this.lock = new ReentrantLock();
		this.parser = new RecommendedTrackParser();
	}
	
	@Override
	public void onerousFunction(Requester app, Tag tag) {
		String url = 
				"http://ws.audioscrobbler.com/2.0/?" +
				"method=tag.gettoptracks&" +
				"tag=" + tag.getName() + "&" +
				"limit=" + TuningParameters.RECOMMENDED_TRACKS_LIMIT + "&" +
				"api_key=8cfeab56c4060f4c3b983902e3903a80&" +
				"format=json";
		List<Track> tracks = this.parser.parse(app.send(url));
		
		this.lock.lock();
		for (Track t : tracks) {
			if (!this.track2ranking.containsKey(t)) {
				this.track2ranking.put(t, tag.getWeight());
			}
			else {
				this.track2ranking.put(t, this.track2ranking.get(t) + tag.getWeight());
			}
		}
		this.lock.unlock();
	}
	
	public Map<Track, Double> getResult() {
		return this.track2ranking;
	}
	
}